<template>
  <view class="brother-b">
    <text class="component-title">组件 B</text>
    <view class="content">
      <input
        type="text"
        v-model="message"
        placeholder="输入要发送给A的内容"
        class="input"
      />
      <button @click="sendToA" class="send-btn">发送给组件A</button>

      <view class="receive-area" v-if="receiveFromA || receiveFromA === ''">
        <text class="receive-label">收到A的消息：</text>
        <text class="receive-content">{{ receiveFromA || "暂无消息" }}</text>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        message: "",
        receiveFromA: "",
        // 保存事件监听的回调引用
        aMessageCallback: null,
      };
    },
    mounted() {
      // 页面加载时注册监听
      console.log("组件B加载，开始监听来自A的消息");

      // 定义回调函数
      this.aMessageCallback = (data) => {
        console.log("组件B收到消息:", data);
        this.receiveFromA = data;
        // 显示提示
        uni.showToast({
          title: "收到A的消息" + this.receiveFromA,
          icon: "none",
          duration: 2000,
        });
      };

      // 注册事件监听
      // uni.$on("message-from-a", this.aMessageCallback);
      this.$eventBus.$on("message-from-a", this.aMessageCallback);
    },
    beforeDestroy() {
      // 页面卸载时移除监听
      console.log("组件B卸载，移除消息监听");
      // uni.$off("message-from-a", this.aMessageCallback);
      this.$eventBus.$off("message-from-a", this.aMessageCallback);
    },
    methods: {
      sendToA() {
        if (!this.message.trim()) {
          uni.showToast({
            title: "请输入内容",
            icon: "none",
          });
          return;
        }

        console.log("组件B发送消息:", this.message);
        // 发送消息到A
        // uni.$emit("message-from-b", this.message);
        this.$eventBus.$emit("message-from-b", this.message);
        // 清空输入框
        this.message = "";
      },
    },
  };
</script>

<style scoped>
  .brother-b {
    background-color: #fff7e6;
    padding: 20rpx;
    border-radius: 10rpx;
  }

  .component-title {
    font-size: 30rpx;
    color: #fa8c16;
    margin-bottom: 20rpx;
    display: block;
  }

  .input {
    width: 100%;
    height: 60rpx;
    border: 1px solid #ddd;
    border-radius: 5rpx;
    padding: 0 10rpx;
    margin-bottom: 15rpx;
    font-size: 28rpx;
    background-color: white;
  }

  .send-btn {
    background-color: #fa8c16;
    color: white;
    margin-bottom: 20rpx;
  }

  .receive-area {
    margin-top: 20rpx;
    padding: 15rpx;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 5rpx;
  }

  .receive-label {
    font-size: 28rpx;
    color: #666;
  }

  .receive-content {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
  }
</style>
